package com.thb.pay.feigin.interceptor;

import com.thb.pay.core.holder.LogContextHolder;
import com.thb.pay.core.logs.utils.LogConstants;
import com.thb.pay.core.utils.ContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Slf4j
@Configuration
public class FeignClientInterceptor implements RequestInterceptor {

    private static final String HEAD_TENANT_KEY = "tenantId";

    private static final String HEAD_USER_KEY = "userId";


    private void transferHeader(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
    }

    public void apply(RequestTemplate requestTemplate) {
        transferHeader(requestTemplate);
        //兼容header未传tenant_id
        if (!(requestTemplate.headers().containsKey(HEAD_TENANT_KEY) && ContextHolder.existTenantId())) {
            requestTemplate.header(HEAD_TENANT_KEY, String.valueOf(ContextHolder.getTenantId()));
        }
        //兼容header未传user_id
        if (!(requestTemplate.headers().containsKey(HEAD_USER_KEY) && ContextHolder.existUserId())) {
            requestTemplate.header(HEAD_USER_KEY, String.valueOf(ContextHolder.getUserId()));
        }

        //链路追踪 日志需要
        if (!(requestTemplate.headers().containsKey(LogConstants.LOG_REQ_ID) && LogContextHolder.existLogReqId())) {
            requestTemplate.header(LogConstants.LOG_REQ_ID, String.valueOf(LogContextHolder.getLogReqId()));
        }
        if (!(requestTemplate.headers().containsKey(LogConstants.REQ_TIME_ID) && LogContextHolder.existReqTimeId())) {
            requestTemplate.header(LogConstants.REQ_TIME_ID, String.valueOf(LogContextHolder.getReqTimeId()));
        }
    }
}